package com.strongbj.iot.devices.newlight.request.handle;

import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.newlight.entity.InventoryTagData;
import com.strongbj.iot.devices.newlight.entity.InventoryTagReturnData;
import com.strongbj.iot.devices.newlight.entity.Tag;
import com.strongbj.iot.devices.newlight.message.NewLightMQMessage;
import com.strongbj.iot.devices.newlight.response.handle.LowBatteryResponseHandle;
import com.strongbj.iot.devices.newlight.service.TagService;
import com.strongbj.iot.mq.producer.TopicSender;

import io.netty.channel.ChannelHandlerContext;

/**
 * 盘点事件
 * 
 * @author lei_w
 *
 */
public class InventoryHandle implements IMessageHandle<NewLightMQMessage, Object> {

	private static Logger logger = LogManager.getLogger(LowBatteryResponseHandle.class.getName());

	private TagService tagService = (TagService) ContextUtils.getBean("tagService");
	
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");

	@Override
	public boolean isHandle(NewLightMQMessage msg) {
		if (msg.getActioncode().equals("inventoryTag")) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, NewLightMQMessage msg) {
		logger.info("====收到盘点命令====");
		InventoryTagData data = ((JSONObject) msg.getPostdata()).toJavaObject(InventoryTagData.class);
		List<String> readers = data.getReaderCode();
		QueryWrapper<Tag> wrapper = new QueryWrapper<Tag>();
		wrapper.in("reader_", readers);
		wrapper.eq("state_", 1);
		List<Tag> onlineTags = tagService.list(wrapper);
		wrapper = new QueryWrapper<Tag>();
		wrapper.in("reader_", readers);
		wrapper.eq("state_", 2);
		List<Tag> offlineTags = tagService.list(wrapper);
		NewLightMQMessage mes = new NewLightMQMessage();
		mes.setActioncode("inventoryTagReturn");
		mes.setGUID(msg.getGUID());
		InventoryTagReturnData rd = new InventoryTagReturnData();
		rd.setReaderCode(readers);
		List<String> onlineLabs = new ArrayList<String>();
		for (Tag t : onlineTags) {
			onlineLabs.add(t.getIp());
		}
		rd.setOnlineLabs(onlineLabs);
		List<String> offlineLabs = new ArrayList<String>();
		for (Tag t : offlineTags) {
			offlineLabs.add(t.getIp());
		}
		rd.setOfflineLabs(offlineLabs);
		mes.setPostdata(rd);
		logger.info("=========inventoryTagReturn=======" + JSON.toJSONString(mes));
		topicSender.send("wh.reader.command.response", JSON.toJSONString(mes));
		return mes;
	}

	@Override
	public void destory() {
		// TODO Auto-generated method stub
		
	}

}
